package io.github.leon406.capp.extension

import io.github.leon406.capp.engine.net.HTTPResponse
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit


/**
 * Author : Leon Shih
 * Time   :2018/8/10 0010 16:49
 * E-mail :deadogone@gmail.com    :
 * Desc   : Rx  Kotlin extension methods
 */
fun <T, R> T.runOnUi(block: T.() -> R) =
        Flowable.just(true)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    block()
                }

fun <T, R> T.runOnIo(block: T.() -> R) =
        Flowable.just(true)
                .observeOn(Schedulers.io())
                .subscribe {
                    block()
                }

fun <T> Flowable<T>.switch2Ui(): Flowable<T> {
    return this.subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
}

fun <T> Observable<T>.switch2Ui(): Observable<T> {
    return this.subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
}


fun Int.timer(): Flowable<Long> {
    return Flowable.interval(1, 1, TimeUnit.SECONDS).take(this.toLong()).map { it + 1 }.switch2Ui()
}

fun Int.countDownTimer(): Flowable<Long> {
    return Flowable.interval(0, 1, TimeUnit.SECONDS).take(this.toLong() + 1).map { this - it }
}

inline fun <reified T> HTTPResponse<T>.real() = HTTPResponse::class.java